<template>
  <el-drawer
    :model-value="modelValue"
    @update:modelValue="handleChange"
    :size="size"
    :before-close="handleBeforeClose"
    direction="rtl"
    destroy-on-close
    :show-close="false"
    class="custom-margin-fix-drawer"
  >
    <template #header>
      <div class="custom-drawer-header">
        <h3 class="el-drawer__title">{{ title }}</h3>
        <el-button
          :icon="CloseBold"
          type="text"
          class="custom-close-btn"
          @click="handleManualClose"
        ></el-button>
      </div>
    </template>

    <template #default>
      <slot name="default"></slot>
    </template>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="type !== 'view'" type="primary" @click="handleSave">
          保存
        </el-button>
        <slot name="extra-footer-actions"></slot>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { CloseBold } from "@element-plus/icons-vue";

const props = defineProps({
  // v-model 绑定抽屉可见性
  modelValue: {
    type: Boolean,
    default: false,
  },
  // 标题：新增/编辑/查看
  title: {
    type: String,
    required: true,
  },
  // 类型：'add' | 'edit' | 'view'
  type: {
    type: String,
    required: true,
  },
  // 抽屉大小
  size: {
    type: [String, Number],
    default: 700,
  },
});

const emit = defineEmits([
  "update:modelValue",
  "save",
  "cancel",
  "close-request",
]);

// 处理 modelValue 变更
const handleChange = (val) => {
  emit("update:modelValue", val);
};

// 抽屉 ESC 键触发
const handleBeforeClose = (done) => {
  emit("close-request", done);
};

// 抽屉头部自定义关闭按钮触发
const handleManualClose = () => {
  emit("close-request", () => {
    emit("update:modelValue", false);
  });
};

// 取消触发
const handleCancel = () => {
  emit("cancel");
};

// 保存触发
const handleSave = () => {
  emit("save");
};
</script>

<style scoped>
:deep(.el-drawer__header) {
  margin-bottom: 5px;
}

.custom-drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-right: 10px;
  margin-bottom: 20px;
  padding-bottom: 15px;

  border-bottom: 1px solid #d9d9d9;
}

.custom-drawer-header .el-drawer__title {
  margin: 0;
  font-weight: 700;
  color: var(--el-text-color-primary);
  font-size: 20px;
}

.custom-drawer-header .custom-close-btn {
  padding: 0;
  min-height: 20px;
  font-size: 20px;
  color: var(--el-color-info);
}

.custom-drawer-header .custom-close-btn:hover {
  color: var(--el-color-primary);
}

:deep(.el-drawer__body) {
  padding: 0 25px 20px 25px;
}
</style>
<style>
.custom-margin-fix-drawer .el-drawer__header {
  margin-bottom: 0px;
}
</style>
